package z_mxsTest.testArxmlSomeip;

import org.w3c.dom.*;
import javax.xml.parsers.*;
import java.io.File;
import java.util.*;
import z_mxsTest.testArxmlSomeip.packages.CherySomeipArxmlParserService;
import z_mxsTest.testArxmlSomeip.common.*;

public class CherySomeipArxmlLoadMain {

    private final List<ArxmlPackageParser> parsers;

    public CherySomeipArxmlLoadMain() {
        parsers = new ArrayList<>();
        initParsers();
    }

    private void initParsers() {
        // 构造时传入所有解析器列表
        parsers.add(new CherySomeipArxmlParserService(parsers));
        // parsers.add(new OtherParser(parsers)); // 添加其他模块解析器
    }

    public void loadArxmlFile(String filePath) {
        try {
            File arxmlFile = new File(filePath);
            if (!arxmlFile.exists()) {
                System.out.println("文件不存在: " + filePath);
                return;
            }

            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(arxmlFile);
            document.getDocumentElement().normalize();

            Element root = document.getDocumentElement();
            Element packagesNode = getFirstChildElement(root, "AR-PACKAGES");

            if (packagesNode == null) {
                System.out.println("未找到 <AR-PACKAGES> 节点");
                return;
            }

            // ✅ 获取所有直接子节点中的 <AR-PACKAGE>
            NodeList packageNodes = packagesNode.getChildNodes();

            for (int i = 0; i < packageNodes.getLength(); i++) {
                Node node = packageNodes.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE && "AR-PACKAGE".equals(node.getLocalName())) {
                    Element packageElement = (Element) node;

                    // 获取当前包名
                    String packageName = XmlParseComm.getTextContent(packageElement, "SHORT-NAME");

                    // 打印根节点信息
                    System.out.println("【Service模块】开始解析: " + packageName);
                    BaseArxmlParser.printRootNode(packageElement.getTagName(), packageName);

                    // 分发给对应解析器处理
                    for (ArxmlPackageParser parser : parsers) {
                        if (parser.supports(packageName)) {
                            parser.parse(packageElement); // 会递归解析
                            break;
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private Element getFirstChildElement(Element parent, String tagName) {
        NodeList list = parent.getElementsByTagName(tagName);
        return list.getLength() > 0 ? (Element) list.item(0) : null;
    }
}
